package com.wang.demo.application.handler;

import com.wang.demo.protocol.message.ChatRequestMessage;
import com.wang.demo.protocol.message.ChatResponseMessage;
import com.wang.demo.service.factory.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author: Jeffrey
 * @date: 2022/01/21/11:40
 * @description:
 */
@ChannelHandler.Sharable
public class PersonChatHandler extends SimpleChannelInboundHandler<ChatRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage msg) throws Exception {
        /*消息目的地*/
        String to = msg.getTo();
        /*获取目的地与服务器建立的Channel*/
        Channel channel = SessionFactory.getSession().getChannel(to);
        if (channel != null){
            /*目的地在线，向目的地Channel 发送消息*/
            channel.writeAndFlush(new ChatResponseMessage(true,msg.getFrom(),msg.getContent()));
        }else{
            /*目的地channel 断开，不在线，向发送者发送响应消息*/
            ctx.writeAndFlush(new ChatResponseMessage(false,"对方用户不在线！"));
        }
    }
}
